package cn.texous.web.parsing.book.strategy.search.fiction;

import cn.texous.util.commons.constant.Result;
import cn.texous.util.commons.util.GsonUtils;
import cn.texous.web.parsing.book.model.bo.publisher.AnaCatalogAddOrUpdateBO;
import cn.texous.web.parsing.book.model.dto.AnaSearchChapterDTO;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParser;
import cn.texous.web.parsing.book.model.resp.AnaSearchCatalogResp;
import cn.texous.web.parsing.book.publisher.fiction.AnaCatalogSubscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/26 13:08
 */
@Slf4j
@Component(CatalogContentProcessor.CCP)
public class CatalogContentProcessor extends AbstractContentProcessor<AnaSearchCatalogResp> {

    /**
     * bean name
     */
    public static final String CCP = "catalogContentProcessor";

    @Override
    public AnaSearchCatalogResp process(Result<String> content,
                                        AnaOriginParser originParser,
                                        Map<String, Object> otherInfo) {
        AnaSearchCatalogResp resp = null;
        if (validateResult(content)) {
            resp = GsonUtils.fromJson(content.getData(), AnaSearchCatalogResp.class);
            // 存储结果
            String anaBookCode = String.valueOf(otherInfo.get("anaBookCode"));
            if (anaBookCode != null)
                catalogAddOrUpdatePublisher(resp.getChapters(), anaBookCode);
        }
        // 返回结果
        return resp;
    }

    private void catalogAddOrUpdatePublisher(List<AnaSearchChapterDTO> chapters,
                                             String anaBookCode) {
        try {
            AnaCatalogAddOrUpdateBO bo = new AnaCatalogAddOrUpdateBO();
            bo.setChapters(chapters);
            bo.setAnaBookCode(anaBookCode);
            anaPublisher.publisher(bo, AnaCatalogSubscribe.TOPIC);
        } catch (Exception e) {
            log.error("章节更新发布失败", e);
        }
    }

}
